package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;


    public void insert(Role record) {
        roleMapper.insert(record);
        //维护关系
        List<Permission> permissions = record.getPermissions();
        if (permissions != null) {
            for (Permission permission : permissions) {
                roleMapper.saveRelation(record.getId(),permission.getId());
            }
        }
        //维护关系
        List<Menu> menus = record.getMenus();
        if (menus != null) {
            for (Menu menu : menus) {
                roleMapper.saveMenuRelation(record.getId(),menu.getId());
            }
        }
    }

    public void updateByPrimaryKey(Role record) {
        roleMapper.updateByPrimaryKey(record);
        //维护关系
        roleMapper.deleteRelation(record.getId());
        List<Permission> permissions = record.getPermissions();
        if (permissions != null) {
            for (Permission permission : permissions) {
                roleMapper.saveRelation(record.getId(),permission.getId());
            }
        }
        //维护关系
        roleMapper.deleteMenuRelation(record.getId());
        List<Menu> menus = record.getMenus();
        if (menus != null) {
            for (Menu menu : menus) {
                roleMapper.saveMenuRelation(record.getId(),menu.getId());
            }
        }
    }

    public List<Role> selectAll() {
        return roleMapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int total = roleMapper.query4Count(qo);
        if (total > 0) {
            return new PageResult(total, roleMapper.query4List(qo));
        }
        return new PageResult(total, Collections.EMPTY_LIST);
    }

    public int deleteByPrimaryKey(Long id) {
        return roleMapper.deleteByPrimaryKey(id);
    }

    public List<Long> getMenuByRoleId(Long roleId) {
        return roleMapper.getMenuByRoleId(roleId);
    }

    public List<String> getRoleByEmployeeId(Long id) {
        return roleMapper.getRoleByEmployeeId(id);
    }

}
